#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<pthread.h>
#include<string.h>

struct client_type{
	int client_sock;
	struct sockaddr_in client_addr;
}client_link_i[20];


void *get_information(void *arg);
void *send_information(void *arg);
char client_information[256]= {'\0'};

int is_new = 0;
int main(int argc,char *argv[])
{
	int base_sock,client_sock;
	int number;
	
	
	pthread_t pthread[21];
	struct sockaddr_in server_addr,client_addr;
	int longth_addr = sizeof(struct sockaddr);
	int reset;	
	for(number = 0;number <20;number++){
		client_link_i[number].client_sock = -1;
	}
	
	//创建套接字
	base_sock = socket(AF_INET,SOCK_STREAM,0);
	printf("socket ok!\n");
	
	//初始化本地地址
	bzero(&server_addr,longth_addr);
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(atoi(argv[1]));
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	bzero(&(server_addr.sin_zero),8);
	printf("init server addr ok!\n");
	
	//绑定套接字
	reset = bind(base_sock,(struct sockaddr *)&server_addr,longth_addr);
	if(reset == 0) printf("bind ok!\n");
		else return -1;
	
	reset = listen(base_sock,20);
	if(reset == 0) printf("listened ok!\n");
		else return -1;
	//
	pthread_create(pthread+20,NULL,send_information,NULL);
	
	while(1){
		do{
			
		    for(number = 0;client_link_i[number].client_sock != -1 && number < 20;number++);
		
		}while(number >= 20);
		
		client_sock = accept(base_sock,(struct sockaddr *)&(client_link_i[number].client_addr),&longth_addr);
		if(client_sock > 0)printf("accept client!\n");
			else{
				printf("accept error\n");
				return -1;
			}
		client_link_i[number].client_sock = client_sock;
		
		
		pthread_create(pthread + number,NULL,get_information,(void *)&client_sock);
		printf("into  pthread %d,%d\n",number,client_sock);
		
	}
	close(base_sock);
	printf("server end\n");
}

	void *get_information(void *arg){
		int client_sock = *(int *)arg;
		char name[20] = {'\0'};
		char inf_base[256] = {'\0'};
		char inf_end[256] = {'\0'};
		int reset;
		printf("connect user!!%d\n",client_sock);
		reset = recv(client_sock,name,sizeof(name),0);
		strcat(name,"::");
		
		while(1){
			bzero(inf_base,sizeof(inf_base));
			bzero(inf_end,sizeof(inf_end));
			while((reset = recv(client_sock,inf_base,sizeof(inf_base),0)) <= 0 )  ;
			strcat(inf_end,name);
			strcat(inf_end,inf_base);
			stpcpy(client_information,inf_end);
			printf("get %s\n",inf_end);
			is_new = 1;
		}
		
		close(client_sock);
		printf("get information end\n");		
	}
	
	void *send_information(void *arg){
		printf("began send !\n");
		int number;
		while(1){
		    while(!is_new);
		    for(number = 0;number < 20;number ++){
			    if(client_link_i[number].client_sock != -1)
			      send(client_link_i[number].client_sock,client_information,sizeof(client_information),0);
		    }
			is_new = 0;
		}
		
	}
	
	
